<template>
	<!-- 账本详细页面 -->
	<view id="accountBook_desc_container">
		<!-- 名称表单 -->
		<uni-forms :modelValue="formData" label-position="left" label-width="50">
			<uni-forms-item label="名称:" name="name">
				<uni-easyinput type="text" v-model="formData.name" placeholder="请输入账本名称" />
			</uni-forms-item>
		</uni-forms>
		<!-- 其他数据的展示 -->
		<view class="order_data_show">
			<view class="show_item">
				<view class="show_item_text">货币类型</view>
				<view class="show_item_value">
					{{ accountBook.currency }}
				</view>
			</view>
			<view class="show_item not_first_item">
				<view class="show_item_text">是否默认</view>
				<view class="show_item_value" v-if="accountBook.isDefault == 1">是</view>
				<view class="show_item_value" v-else>否</view>
			</view>
			<view class="show_item not_first_item">
				<view class="show_item_text">创建时间</view>
				<view class="show_item_value">
					{{ accountBook.createTime }}
				</view>
			</view>
		</view>
		<!-- 账本操作 设置默认 和 删除账本 -->
		<view class="option_box">
			<view class="option_set_default option_box_item" @click="setDefaultHandle">
				<view class="option_set_default_left">设为默认账本</view>
				<view class="option_set_default_right right_icon">
					<image src="../../static/common/right.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="option_delete option_box_item" @click="deleteHandle">
				<view class="option_delete_left">删除账本</view>
				<view class="option_delete_right right_icon">
					<image src="../../static/common/right.png" mode="widthFix"></image>
				</view>
			</view>
		</view>
		<!-- 保存按钮，点击后修改名称 -->
		<view class="btn-box">
			<button type="primary" style="background-color: #e69626;" @click="saveHandle">保存</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import dayjs from 'dayjs';

// 账本数据
let accountBook = ref({});
// 表单数据
let formData = ref({
	name: ''
});

onLoad((options) => {
	// 反序列化账本数据为对象
	accountBook.value = JSON.parse(options.bookData);
	let pageTitle = `${accountBook.value.name} · 设置`;

	// 将时间格式化之后再赋值
	accountBook.value.createTime = dayjs(accountBook.value.createTime).format('YYYY-MM-DD HH:mm::ss');

	formData.value.name = accountBook.value.name;

	console.log('--=', accountBook.value);

	// 动态设置页面标题
	uni.setNavigationBarTitle({
		title: pageTitle
	});
});

// 设置默认账本 处理器
function setDefaultHandle() {
	uni.showModal({
		title: '提示',
		content: '确定将此账本设置默认吗？',
		success: function (res) {
			if (res.confirm) {
				setDefaultExecute();
			} else if (res.cancel) {
				uni.$showT('取消设置默认');
			}
		}
	});
}

// 设置默认 - 执行器
async function setDefaultExecute() {
	// 判断当前账本是否为默认
	if (accountBook.value.isDefault == 1) {
		uni.$showT('当前账本已是默认账本');
		return 1;
	}

	const res = await uni.$http.put(`/accountBooks/setDefault/${accountBook.value.id}`);
	if (res.data.code == 0) {
		uni.$showT(res.data.msg);
		return 0;
	}

	// 手动更新前端状态
	accountBook.value.isDefault = 1;

	afterHandle();
	uni.$showT("设置成功");
}

// 删除账本处理器
function deleteHandle() {
	uni.showModal({
		title: '提示',
		content: '删除操作不可逆，请再次确定是否删除？',
		success: function (res) {
			if (res.confirm) {
				deleteExecute();
			} else if (res.cancel) {
				uni.$showT('取消删除操作');
			}
		}
	});
}

// 执行删除
async function deleteExecute() {
	let userInfo = JSON.parse(uni.getStorageSync('userInfo'));

	// 判断此账本是否为正在选择的账本
	if (accountBook.value.name == uni.getStorageSync('selectedBook')) {
		// 获取当前用户的所有账本
		let accountBookData = uni.getStorageSync('accountBookData');

		console.log('删除账本为当前选择的账本');
		// 获取候选账本，按顺序设置为“选择的账本”
		let notDeleteBooks = accountBookData.filter((item) => {
			return item.id != accountBook.value.id;
		});

		console.log('开始自动选择账本，候选账本：', notDeleteBooks);
		// 执行删除
		const res = await uni.$http.delete(`/accountBooks/${userInfo.id}/${accountBook.value.id}`);
		// 删除成功，取候选账本中的第一个账本为 已选择的账本。
		uni.setStorageSync('selectedBook', notDeleteBooks[0].name);
		afterHandle();
		deleteAfterHandle();
	} else {
		const res = await uni.$http.delete(`/accountBooks/${userInfo.id}/${accountBook.value.id}`);
		afterHandle();
		deleteAfterHandle();
	}
}

// 删除后置处理器
function deleteAfterHandle() {
	// 删除后，自动跳转
	uni.$showT('删除成功，即将跳转...');
	setTimeout(() => {
		uni.navigateTo({
			url: '/subPkg1/account_book/account_book'
		});
	}, 1500);
}

// 后置处理器
async function afterHandle() {
	// 删除成功后刷新数据
	let userInfo = JSON.parse(uni.getStorageSync('userInfo'));
	const res = await uni.$http.get(`/accountBooks/getAllByOpenId?openId=${userInfo.openid}`);
	// TODO通过默认账本字段排序
	uni.setStorageSync('accountBookData', res.data.data);
}

// 保存处理器
async function saveHandle(){
	const res = await uni.$http.put(`/accountBooks/updateBookName/${accountBook.value.id}/${formData.value.name}`);
	if(res.data.code == 0){
		uni.$showT("保存失败");
		return 0;
	}
	
	// 判断是否为当前选择的账本，如果是，需要将新名称替换上
	if(uni.getStorageSync("selectedBook") == accountBook.value.name){
		uni.setStorageSync("selectedBook", formData.value.name);
	}
	
	uni.$showT("保存成功，即将返回...");
	setTimeout(()=>{
		uni.navigateBack();
	}, 1500);
	
	afterHandle();
}
</script>

<style lang="scss" scoped>
#accountBook_desc_container {
	width: 97%;
	margin: 0 auto;
	margin-top: 10px;
	position: relative;
}

.show_item {
	display: flex;
	justify-content: space-between;
	padding: 30rpx 20rpx;
	background-color: #fff;
	font-size: 14px;
}

.show_item_value {
	font-size: 13px;
	color: #5f5f5f;
}

.not_first_item {
	border-top: solid 1px #dcdcdc;
}

.option_box {
	margin-top: 10px;
}

.option_box_item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 20rpx;
	background-color: #fff;
	font-size: 14px;
	font-weight: 600;
}

.option_delete {
	border-top: solid 1px #dcdcdc;
}

.right_icon image {
	width: 25px;
}

.option_set_default_left {
	color: #050d14;
}

.option_delete_left {
	color: red;
}

.btn-box{
	position: fixed;
	bottom: 0px;
	width: 97vw;
}
</style>
